import json

from django.conf import settings
from django.contrib.auth import login, logout
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import View
from django import http


from redis import StrictRedis
from django_redis import get_redis_connection
import logging

from IHome.utils.fastdfs.demo import client
from IHome.utils.response_code import RET
from apps.users.models import User

logger = logging.getLogger('django')

class Register(View):
    '''用户注册'''

    def post(self, request):
        # 1. 获取参数并进行参数校验
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get("mobile")  # 获取手机号
        phonecode = data_dict.get("phonecode")  # 获取短信验证码
        password = data_dict.get("password")  # 密码
        password2 = data_dict.get('password2')  # 密码2

        # 判断参数是否完整
        if not all([mobile, phonecode, password, password2]):
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数不全"})

        # 判断密码是否一致
        if password != password2:
            return http.JsonResponse({'errno': RET.PWDERR, 'errmsg': "密码不一致"})

        # 2. 从redis中获取指定手机号对应的短信验证码的
        redis_conn = get_redis_connection('verify_code')  # type: StrictRedis
        try:
            sms_code = redis_conn.get("SMS_" + mobile)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "获取本地验证码失败"})

        if not sms_code:
            return http.JsonResponse({'errno': RET.NODATA, 'errmsg': "短信验证码过期"})

        # 3. 校验验证码
        if phonecode != sms_code.decode():
            return http.JsonResponse({'errno': RET.DATAERR, 'errmsg': "短信验证码错误"})

        # 4. 初始化 user 模型，并设置数据并添加到数据库
        try:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': RET.DATAERR, 'errmsg': "用户创建失败"})

        # 状态保持
        login(request, user)
        return http.JsonResponse({'errno': 0, 'errmsg': "注册成功"})

#用户登录实现API
class LoginView(View):
    def post(self, request):
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get('mobile')
        password = data_dict.get('password')

        if not all([mobile, password]):
            return http.JsonResponse({'errno': 4103, 'errmsg': '请填写账户或密码'})
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            return http.JsonResponse({'errno': 4001, 'errmsg': '无用户'})
        if not user.check_password(password):
            return http.JsonResponse({'errno': 4106, 'errmsg': "密码错误"})
        # 保持登录状态
        login(request, user)
        return http.JsonResponse({'errno': 0, 'errmsg': '登录成功'})


# 获取登录状态API
class SessionView(View):
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            data = {'user_id': user.id, 'name': user.username}
            return http.JsonResponse({'errno': 0, 'errmsg': "OK", 'data': data})
        else:
            return http.JsonResponse({'errno': 4101, 'errmsg': '用户未登录'})


# 退出登录ＡＰＩ
class LogoutView(View):
    def delete(self, reqouet):
        logout(reqouet)

        return http.JsonResponse({'errno': 0, 'errmsg': '用户已退出'})



class UserProfile(View):
    def get(self, request):
        # 获取用户信息
        user = request.user

        data = {
            "name": user.username,
            "avatar_url": user.avatar_url,
            "mobile": user.mobile
        }

        return JsonResponse({'errno': 0, 'errmsg': "OK", 'data': data})

    def post(self, request):
        user = request.user
        # 用户名修改
        data_dict = json.loads(request.body.decode())
        name = data_dict.get('name')

        if not name:
            return JsonResponse({'errno': 4002, 'errmsg': "无参数！"})

        try:
            user.username = name
            user.save()

        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': "修改失败！"})

        return JsonResponse({'errno': 0, 'errmsg': "修改成功！"})

class UserAvatar(View):
    def post(self, request):
        user = request.user
        # 接收上传的文件
        content = request.FILES.get("avatar")
        if not content:
            return JsonResponse({'errno': 4002, 'errmsg': "无参数！"})
        # 将文件上传到FastDFs
        # 创建客户端对象
        # 调用上传函数返回结果
        try:
            image = content.read()
            result = client.upload_by_buffer(image)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': "数据错误！"})
        # 返回数据,拼接图片路径
        file_id = result.get('Remote file_id')
        url = settings.FDFS_BASE_URL+ file_id
        # 将图像保存到数据库
        try:
            user.avatar_url = url
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': "保存失败！"})
        data = {
            "avatar_url": url
        }
        # 返回结果
        return JsonResponse({'errno': 0, 'errmsg': "保存成功！", "data": data})


class AuthProfile(View):
    def get(self,request):
        # 1.取到当前登录用户
        user = request.user
        # 2.获取当前用户的认证信息
        auth_dict = {
            "real_name": user.real_name,
            "id_card": user.id_card
        }
        # 3.返回信息
        return JsonResponse({'errno':0, 'errmsg': "OK", 'data': auth_dict})

    def post(self, request):

        user = request.user

        # 接收参数
        data_dict = json.loads(request.body.decode())
        real_name = data_dict.get('real_name')
        id_card = data_dict.get('id_card')

        # 修改数据
        try:
            user.real_name = real_name
            user.id_card = id_card
            user.save()

        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': "修改失败！"})

        return JsonResponse({'errno': 0, 'errmsg': "修改成功！"})



